package ink.tiptop.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * 2020年4月5日09:36:19
 * zjf
 * 2020年4月7日10:49:16
 * 工厂类测试OJBK
 * @author zhongjiafeng
 */
@Component(value = "factoryBeanHandler")
@Slf4j
public class FactoryBeanHandler implements ApplicationContextAware, InitializingBean {

    @Autowired
    private SimpleServiceFactory factory;

    private ApplicationContext applicationContext;

    public FactoryBeanHandler() {
        log.error("初始化:FactoryBeanHandler");
    }

    @Override
    public void afterPropertiesSet() {
        scanMyFactoryBeanClass();
    }

    /**
     * 查找 用 MyFactoryBean 注解的 类
     *
     * @throws Exception
     */
    private void scanMyFactoryBeanClass() {
        final Map<String, Object> permissionMap = applicationContext.getBeansWithAnnotation(FactoryBean.class);
        for (final Object permissionObject : permissionMap.values()) {
            final Class<? extends Object> permissionClass = permissionObject.getClass();
            final FactoryBean annotation = permissionClass.getAnnotation(FactoryBean.class);
            if (annotation != null) {
                // 作为一个需要注入工厂标记接口
                /*if (permissionObject instanceof ICmdService) {
                    factory.addService(annotation.cmdType(),permissionObject);
                }*/
                factory.addService(annotation.cmdType(),permissionObject);
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
